package com.web;

import com.domain.User;
import com.service.userService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 员工的注册
 * 接收 registEmployee.jsp 页面的表单数据，一个个接收，封装成Employee对象
 * 提交到 employeeService 的 regist 函数，
 * 转发到/loginEmployee.jsp页面，进行重新登录
 */
@WebServlet("/registUser")
public class RegistUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("客户注册");

        //1.解决乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        //2.接受参数
        Map<String, String[]> map = request.getParameterMap();

        //3.封装对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //4.将数据存储到数据库里面，调用service层
        Integer integer = new userService().addUser(user);

        //5.判断是否成功
        PrintWriter out = response.getWriter();
        if(integer ==0){
            //用户名重复
            out.write("注册失败！");
            System.out.println("员工"+user.getUserName()+"注册失败");
        }else {
            //注册成功
            response.sendRedirect(request.getContextPath()+"/LoginUser.jsp");//重定向
            System.out.println("员工"+user.getUserName()+"注册成功");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
